package dht.mains;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Scanner;

import dht.data.DhtData;
import dht.node.Node;

public class MenuEtToutEtTout {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		
		int dim = -1;
		String critere = "", squeTaDis = "";
		ArrayList<String> lstCritere = null;

		Node mySelf = null;

		if(args.length < 3){
			System.out.println("Usage : PgmDHT dimension [true|false] AddressIP");
			System.exit(1);
		}
		else{

			dim = Integer.parseInt(args[0]);
			boolean init = Boolean.parseBoolean(args[1]);
			String adrrIp = args[2];

			try {
				mySelf = new Node(dim,init,adrrIp); 
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			mySelf.start();
			mySelf.readyToWork();
		}

		while (mySelf.readyWork==false) {
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {}
		}
		do{
			System.out.print("Le menu et tout et tout : \n\n" +
					" [1] Put message\n" +
					" [2] Get message\n" +
					" [3] Quitter la DHT\n" +
			"> ");

			squeTaDis = sc.nextLine();

			sc.reset();

			if(squeTaDis.compareTo("1") == 0){
				
				lstCritere = new ArrayList<String>();
				
				for(int i=0; i<dim ;i++){
					System.out.print("Critere dimension " + (i+1) + ": ");
					critere = sc.nextLine();
					lstCritere.add(critere);
				}

				System.out.print("\nEntrez valeur : ");

				squeTaDis = sc.nextLine();

				mySelf.PUT(lstCritere,new DhtData<Integer>(Integer.parseInt(squeTaDis)));
				System.out.println("PUT envoye !\n");
			}
			else if(squeTaDis.compareTo("2") == 0){
				
				lstCritere = new ArrayList<String>();
				
				for(int i=0; i<dim ;i++){
					System.out.print("Critere dimension " + (i+1) + " : ");
					critere = sc.nextLine();
					lstCritere.add(critere);
				}
				
				DhtData<Integer> res = mySelf.GET(lstCritere);
				
				if(res != null)
					System.out.print("\nResultat : " + res.getValue() + "\n");
				else
					System.out.println("\nLa donne n'existe pas\n");
				
			}	

		}while(squeTaDis.compareTo("3") != 0);

		mySelf.QUIT();

		System.out.println("Bye !");
	}

}
